package struts2.action;

import java.util.Map;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import DAO.DaoLogin;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class GetPassAction extends ActionSupport {
	private String username;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	private String email;

	public String execute() {
		String pass = DaoLogin.getPassword(username, email);
		if (pass != null) {
			String[] recipients = new String[] {email };
            String subject = "Get Passwood!";
            String message = "Your Password : "+pass;
            String from = "thanhcongptit@gmail.com";
			try {
				sendMail(recipients, subject, message, from);
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "success";
		} else {
			addActionError(getText("error.forgot"));
			return "error";
		}
	}

	public void sendMail(String recipients[], String subject, String message,
			String from) throws MessagingException {
		boolean debug = false;

		// Set the host smtp address like String SMTPHost = "192.168.14.123";
		String SMTPHost = "SMTP Server Host address";

		// Create properties object
		Properties properties = new Properties();

		// Set mail SMTP host in properties
		properties.put("mail.smtp.host", SMTPHost);

		// getting Session
		Session session = Session.getDefaultInstance(properties, null);
		session.setDebug(debug);

		// create a message
		Message msg = new MimeMessage(session);

		// Setting sender and Recipients address
		InternetAddress addressFrom = new InternetAddress(from);
		msg.setFrom(addressFrom);

		// Adding all recipients
		InternetAddress[] addressTo = new InternetAddress[recipients.length];
		for (int i = 0; i < recipients.length; i++) {
			addressTo[i] = new InternetAddress(recipients[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addressTo);

		// Setting e-mail header
		msg.addHeader("MailingApplication", "Get Password");

		// Setting the Subject and Content Type
		msg.setSubject(subject);
		msg.setContent(message, "text/html");
		Transport.send(msg);
	}
}
